//
//  LSZAddedIndustryManagementVC.m
//  PartyClassCloud
//
//  Created by 梁素珍 on 2018/10/27.
//  Copyright © 2018年 九酷. All rights reserved.
//

#import "LSZAddedIndustryManagementVC.h"
#import "LYSDatePickerController.h"

@interface LSZAddedIndustryManagementVC ()<UITableViewDelegate,UITableViewDataSource,UITextFieldDelegate,UITextViewDelegate,LDImagePickerDelegate,LYSDatePickerSelectDelegate>
@property(nonatomic,strong)TPKeyboardAvoidingScrollView * backScrollView;
@property(nonatomic,strong) UITableView * tableViewConferenceClass;
@property(nonatomic,strong) NSArray * arrayTitle;

@property(nonatomic,strong) NSString * imageStrOne;
@property(nonatomic,strong) NSString * imageStrTwo;
@property(nonatomic,strong) NSString * imageStrThree;
@property(nonatomic,assign) NSInteger chooseWhatImageView;

@property(nonatomic,strong) NSString * timeString;

@end

@implementation LSZAddedIndustryManagementVC

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.timeString = [self getCurrentTimes];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"添加产业";
    self.imageStrOne = @"";
    self.imageStrTwo = @"";
    self.imageStrThree = @"";
    self.arrayTitle = @[@"标题",@"上传时间",@"发布人",@"内容"];
    self.backScrollView = [[TPKeyboardAvoidingScrollView alloc] initWithFrame:CGRectMake(0,NAVIGATION_BAR_HEIGHT, ScreenWidth,ScreenHeight-NAVIGATION_BAR_HEIGHT)];
    self.backScrollView.userInteractionEnabled = YES;
    [self.view addSubview:self.backScrollView];
    
    [self.tableViewConferenceClass registerClass:[LSZThreeContentTableViewCell class] forCellReuseIdentifier:@"LSZThreeContentTableViewCell"];
    [self.tableViewConferenceClass registerClass:[LSZParticipantsTableViewCell class] forCellReuseIdentifier:@"LSZParticipantsTableViewCell"];
    [self.tableViewConferenceClass registerClass:[LSZBasicInformationTableViewCell class] forCellReuseIdentifier:@"LSZBasicInformationTableViewCell"];
    UIBarButtonItem *rightBarItem = [[UIBarButtonItem alloc]initWithTitle:@"发布" style:UIBarButtonItemStylePlain target:self action:@selector(threeReleased)];
    self.navigationItem.rightBarButtonItem = rightBarItem;
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(ConferenceClassClick)];
    [self.view addGestureRecognizer:tapGesture];
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.arrayTitle.count;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row <2) {
        return 50;
    }else if (indexPath.row == 2){
        return 150;
    }else{
        return 230;
    }
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row <2) {
        LSZBasicInformationTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"LSZBasicInformationTableViewCell" forIndexPath:indexPath];
        if (indexPath.row == 1) {
            cell.textFieldContent.hidden = YES;
            cell.labelContent.hidden = NO;
            if ((NullStringjudgment(NSStr(self.timeString))).length > 0) {
                cell.labelContent.text = self.timeString;
            }else{
                cell.labelContent.text = [self getCurrentTimes];
            }
            UITapGestureRecognizer * tapTimeGes = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(timeChooseClick)];
            [cell addGestureRecognizer:tapTimeGes];
        }else{
            cell.textFieldContent.placeholder = self.arrayTitle[indexPath.row];
            cell.textFieldContent.hidden = NO;
            cell.labelContent.hidden = YES;
            cell.textFieldContent.delegate = self;
        }
        cell.labelTitle.text = self.arrayTitle[indexPath.row];
        cell.contentView.backgroundColor = RGBColor(236, 236, 236);
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    }else if (indexPath.row == 2){
        LSZParticipantsTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"LSZParticipantsTableViewCell" forIndexPath:indexPath];
        cell.textViewContent.delegate = self;
        cell.contentView.backgroundColor = RGBColor(236, 236, 236);
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    }else{
        LSZThreeContentTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"LSZThreeContentTableViewCell" forIndexPath:indexPath];
        cell.textViewContent.delegate = self;
        cell.contentView.backgroundColor = RGBColor(236, 236, 236);
        if (self.imageStrOne.length == 0) {
            cell.imageViewOne.hidden = NO;
            cell.imageViewTwo.hidden = YES;
            cell.imageViewThree.hidden = YES;
            cell.imageViewOne.image = [UIImage imageNamed:@"添加图片"];
            cell.imageViewTwo.image = [UIImage imageNamed:@"添加图片"];
            cell.imageViewThree.image = [UIImage imageNamed:@"添加图片"];
        }else if (self.imageStrTwo.length == 0){
            cell.imageViewOne.hidden = NO;
            cell.imageViewTwo.hidden = NO;
            cell.imageViewThree.hidden = YES;
            [cell.imageViewOne sd_setImageWithURL:[NSURL URLWithString:self.imageStrOne] placeholderImage:[UIImage imageNamed:@"默认"]];
            cell.imageViewTwo.image = [UIImage imageNamed:@"添加图片"];
            cell.imageViewThree.image = [UIImage imageNamed:@"添加图片"];
        }else if (self.imageStrThree.length == 0){
            cell.imageViewOne.hidden = NO;
            cell.imageViewTwo.hidden = NO;
            cell.imageViewThree.hidden = NO;
            [cell.imageViewOne sd_setImageWithURL:[NSURL URLWithString:self.imageStrOne] placeholderImage:[UIImage imageNamed:@"默认"]];
            [cell.imageViewTwo sd_setImageWithURL:[NSURL URLWithString:self.imageStrTwo] placeholderImage:[UIImage imageNamed:@"默认"]];
            cell.imageViewThree.image = [UIImage imageNamed:@"添加图片"];
        }
        else{
            cell.imageViewOne.hidden = NO;
            cell.imageViewTwo.hidden = NO;
            cell.imageViewThree.hidden = YES;
            [cell.imageViewOne sd_setImageWithURL:[NSURL URLWithString:self.imageStrOne] placeholderImage:[UIImage imageNamed:@"默认"]];
            [cell.imageViewTwo sd_setImageWithURL:[NSURL URLWithString:self.imageStrTwo] placeholderImage:[UIImage imageNamed:@"默认"]];
            [cell.imageViewThree sd_setImageWithURL:[NSURL URLWithString:self.imageStrThree] placeholderImage:[UIImage imageNamed:@"默认"]];
        }
        cell.imageViewOne.userInteractionEnabled = YES;
        cell.imageViewTwo.userInteractionEnabled = YES;
        cell.imageViewThree.userInteractionEnabled = YES;
        
        UITapGestureRecognizer * tapChooseOne = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(ChooseOneClick)];
        [cell.imageViewOne addGestureRecognizer:tapChooseOne];
        
        UITapGestureRecognizer * tapChooseTwo = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(ChooseTwoClick)];
        [cell.imageViewTwo addGestureRecognizer:tapChooseTwo];
        
        UITapGestureRecognizer * tapChooseThree = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(ChooseThreeClick)];
        [cell.imageViewThree addGestureRecognizer:tapChooseThree];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    }
}
#pragma mark - 发布三会一课内容
-(void)threeReleased
{
    LSZBasicInformationTableViewCell * cellOne = (LSZBasicInformationTableViewCell *)[self.tableViewConferenceClass cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0  inSection:0]];
    LSZBasicInformationTableViewCell * cellThree = (LSZBasicInformationTableViewCell *)[self.tableViewConferenceClass cellForRowAtIndexPath:[NSIndexPath indexPathForRow:1  inSection:0]];
    LSZParticipantsTableViewCell * cellFive = (LSZParticipantsTableViewCell *)[self.tableViewConferenceClass cellForRowAtIndexPath:[NSIndexPath indexPathForRow:2  inSection:0]];
    LSZThreeContentTableViewCell * cellSix = (LSZThreeContentTableViewCell *)[self.tableViewConferenceClass cellForRowAtIndexPath:[NSIndexPath indexPathForRow:3  inSection:0]];
    if (NSStr(cellOne.textFieldContent.text).length == 0) {
        [self initWithtring:@"请填写标题!"];
        return;
    }
    if (NSStr(cellThree.labelContent.text).length == 0) {
        [self initWithtring:@"请填写上传时间!"];
        return;
    }
    if (NSStr(cellFive.textViewContent.text).length == 0) {
        [self initWithtring:@"请填写发布人!"];
        return;
    }
    if (NSStr(cellSix.textViewContent.text).length == 0) {
        [self initWithtring:@"请填写内容!"];
        return;
    }
    NSString * urlIma = [[NSString alloc]init];
    if (![NullStringjudgment(NSStr(self.imageStrThree)) isEqualToString:@""]) {
        urlIma = [NSString stringWithFormat:@"%@,%@,%@",self.imageStrOne,self.imageStrTwo,self.imageStrThree];
    }else if(![NullStringjudgment(NSStr(self.imageStrTwo)) isEqualToString:@""]){
        urlIma = [NSString stringWithFormat:@"%@,%@",self.imageStrOne,self.imageStrTwo];
    }else if (![NullStringjudgment(NSStr(self.imageStrOne)) isEqualToString:@""]){
        urlIma = self.imageStrOne;
    }
    else{
        [self initWithtring:@"至少上传一张图片!"];
        return;
    }
    [LSZRequestData initWithReleaseIndustryManagement:cellOne.textFieldContent.text activityTime:cellThree.labelContent.text  personNames:cellFive.textViewContent.text content:cellSix.textViewContent.text coverUrl:urlIma :^(BOOL isOk, NSString * str, NSString * string) {
        if (isOk == YES) {
            [self initWithtring:@"发布成功!"];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [self.navigationController popViewControllerAnimated:YES];
            });
        }
    }];
    
}
#pragma mark - 选择时间
-(void)timeChooseClick
{
    [LYSDatePickerController alertDatePickerInWindowRootVC];
    [LYSDatePickerController customPickerDelegate:self];
    [LYSDatePickerController customdidSelectDatePicker:^(NSDate *date) {
        NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
        [dateFormat setDateFormat:@"yyyy-MM-dd HH:mm"];
        NSString *currentDate = [dateFormat stringFromDate:date];
        LSZBasicInformationTableViewCell * cellThree = (LSZBasicInformationTableViewCell *)[self.tableViewConferenceClass cellForRowAtIndexPath:[NSIndexPath indexPathForRow:2  inSection:0]];
        cellThree.labelContent.text = currentDate;
        self.timeString = currentDate;
    }];
}
#pragma mark - 上传图片
-(void)ChooseOneClick
{
    self.chooseWhatImageView = 1;
    [self ModifyThePicture];
}
-(void)ChooseTwoClick
{
    self.chooseWhatImageView = 2;
    [self ModifyThePicture];
}
-(void)ChooseThreeClick
{
    self.chooseWhatImageView = 3;
    [self ModifyThePicture];
}
#pragma mark - 修改头像
-(void)ModifyThePicture
{
    __weak typeof(self) weakSelf = self;
    [weakSelf ConferenceClassClick];
    ACActionSheet *actionSheet = [[ACActionSheet alloc] initWithTitle:nil cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@[@"相册",@"拍照"] actionSheetBlock:^(NSInteger buttonIndex) {
        if(buttonIndex ==0) {
            [weakSelf initWithPhoneFromThePhotoAlbum];
        }else if (buttonIndex == 1){
            [weakSelf initWithPhoneTakingpictures];
        }
    }];
    [actionSheet show];
}
#pragma mark - 拍照
-(void)initWithPhoneTakingpictures
{
    NSUInteger sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    // 判断是否支持相机
    if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        sourceType = UIImagePickerControllerSourceTypeCamera;
    }
    else {
        [self initWithtring:@"此设备没有摄像功能!"];
        return;
    }
    // 跳转到相机或相册页面
    LDImagePicker *imagePicker = [LDImagePicker sharedInstance];
    imagePicker.delegate = self;
    //设置宽高比scale来设置剪切框大小，剪切框宽度固定为屏幕宽度
    [imagePicker showImagePickerWithType:0   InViewController:self Scale:1];
}
#pragma mark - 从相册里面查找
-(void)initWithPhoneFromThePhotoAlbum
{
    NSUInteger sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    // 判断是否支持相机
    if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        //来源:相册//来自图库
        sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        ALAuthorizationStatus author = [ALAssetsLibrary authorizationStatus];
        if (author == ALAuthorizationStatusRestricted || author == ALAuthorizationStatusDenied){
            //无权限
            [self initWithtring:@"照片访问受限,请允许app访问你的照片!"];
            return;
        }
    }
    else {
        //来自相册
        sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
        ALAuthorizationStatus author = [ALAssetsLibrary authorizationStatus];
        if (author == ALAuthorizationStatusRestricted || author == ALAuthorizationStatusDenied){
            //无权限
            [self initWithtring:@"照片访问受限,请允许app访问你的照片!"];
            return;
        }
    }
    // 跳转到相机或相册页面
    LDImagePicker *imagePicker = [LDImagePicker sharedInstance];
    imagePicker.delegate = self;
    //设置宽高比scale来设置剪切框大小，剪切框宽度固定为屏幕宽度
    [imagePicker showImagePickerWithType:1   InViewController:self Scale:1];
}
- (void)imagePicker:(LDImagePicker *)imagePicker didFinished:(UIImage *)editedImage{
    UIImage *imagestr = editedImage;
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
    NSString *filePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:[NSString stringWithFormat:@".png"]];   // 保存文件的名称
    BOOL result = [UIImagePNGRepresentation(imagestr)writeToFile: filePath    atomically:YES]; // 保存成功会返回YES
    LSZThreeContentTableViewCell * cell = (LSZThreeContentTableViewCell *)[self.tableViewConferenceClass cellForRowAtIndexPath:[NSIndexPath indexPathForRow:5  inSection:0]];
    if (self.chooseWhatImageView == 1) {
        cell.imageViewOne.image = editedImage;
        cell.imageViewTwo.hidden = NO;
    }else if (self.chooseWhatImageView == 2){
        cell.imageViewTwo.image = editedImage;
        cell.imageViewThree.hidden = NO;
        
    }else{
        cell.imageViewThree.image = editedImage;
        
    }
    //需要在此处上传服务器
    __weak typeof(self) weakSelf = self;
    [LSZRequestData UploadFile:filePath imageView:editedImage :^(BOOL isOk, NSString * string, NSString * str) {
        if (isOk == YES) {
            if (self.chooseWhatImageView == 1) {
                self.imageStrOne = str;
            }else if (self.chooseWhatImageView == 2){
                self.imageStrTwo = str;
            }else{
                self.imageStrThree = str;
            }
        }else{
            [weakSelf initWithtring:@"图片上传失败!"];
        }
    }];
}
//用户点击图像选取器中的“cancel”按钮时被调用，这说明用户想要中止选取图像的操作
-(void)imagePickerDidCancel:(LDImagePicker *)imagePicker
{
}
-(void)ConferenceClassClick
{
    [self.view endEditing:YES];
}
-(UITableView *)tableViewConferenceClass
{
    if (_tableViewConferenceClass == nil) {
        _tableViewConferenceClass = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, [[UIScreen mainScreen] bounds].size.width , [[UIScreen mainScreen] bounds].size.height) style:UITableViewStylePlain];
        _tableViewConferenceClass.delegate = self;
        _tableViewConferenceClass.dataSource = self;
        _tableViewConferenceClass.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableViewConferenceClass.estimatedRowHeight=0;
        _tableViewConferenceClass.estimatedSectionFooterHeight =0;
        _tableViewConferenceClass.estimatedSectionHeaderHeight =0;
        _tableViewConferenceClass.backgroundColor = RGBColor(236, 236, 236);
        [_tableViewConferenceClass setSeparatorInset:UIEdgeInsetsMake(0, 20, 0, 20)];
        [self.backScrollView addSubview:_tableViewConferenceClass];
    }
    return _tableViewConferenceClass;
}
-(NSString*)getCurrentTimes{
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    // ----------设置你想要的格式,hh与HH的区别:分别表示12小时制,24小时制
    [formatter setDateFormat:@"YYYY-MM-dd HH:mm"];
    //现在时间,你可以输出来看下是什么格式
    NSDate *datenow = [NSDate date];
    NSString *currentTimeString = [formatter stringFromDate:datenow];
    NSLog(@"currentTimeString =  %@",currentTimeString);
    
    return currentTimeString;
    
}

@end
